<?php

namespace app\admin\controller\bomlists;

use app\common\controller\Backend;
use Think\Db;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Bomlist extends Backend
{
    
    /**
     * Bomlist模型对象
     * @var \app\admin\model\bomlists\Bomlist
     */
    protected $model = null;
    protected $searchFields = 'id,p_bn';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\bomlists\Bomlist;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->getAccessList =$this->model->getAccessList();
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $total = $this->model
//                    ->with(['products'])
//                    ->where($where)
//                    ->order($sort, $order)
//                    ->count();

            $list = $this->model
                    ->with(['products'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {

                
            }
            $list = collection($list)->toArray();
            $res = array();
            foreach ($list as $key => $val) {
                $res[$val['p_bn']] = $val;
            }
            $result = array("total" => count($res), "rows" => array_values($res));

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');
            $products = $this->request->post("products/a",[],'trim');
            if(!isset($params['product']) || !$params['product']){
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $where['p_bn'] = $params['product'];
            $has_product = $this->model->where($where)->find();
            if(!empty($has_product)){
                $this->error($params['product'].__('Product were exit', ''));
            }
            if(!isset($products) || empty($products)){
                $this->error(__('Parameter %s can not be empty', ''));
            }
            foreach($products as $key => $val){
                if(!$val['Dosage'] || empty($val['Dosage'])){
                    $this->error($key.__('Usage cannot be empty', ''));
                }
                $data[] = array(
                    'p_bn' => $params['product'],
                    'c_bn' => $key,
                    'level' => 1,
                    'createtime' => time(),
                    'updatetime' => time(),
                    'status' => $params['status'],
                    'unit' => $val['unit'],
                    'Dosage' => $val['Dosage'],
                    'comment' => $val['comment']
                );
            }
            Db::startTrans();
            $result = $this->model->insertAll($data);
            if($result){
                Db::commit();
                $this->success();
            }else{
                Db::rollback();
                $this->error(__('Operation failed', ''));
            }
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     * @param null $ids
     * @param null $status
     */
    public function edit($ids = null,$status = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');
            $products = $this->request->post("products/a",[],'trim');
            if(!isset($params['product']) || !$params['product']){
                $this->error(__('Parameter %s can not be empty', ''));
            }
//            $where['p_bn'] = $params['product'];
//            $has_product = $this->model->where($where)->find();
//            if(!empty($has_product)){
//                $this->error($params['product'].__('Product were exit', ''));
//            }
            if(isset($products['newbom'])){
                $newbom = $products['newbom'];
                unset($products['newbom']);
            }
            if((!isset($products) || empty($products)) && (!isset($newbom) || empty($newbom))){
                $this->error(__('Parameter %s can not be empty', ''));
            }
            //新增数据与更新数据判重
            if((isset($products) && !empty(isset($products))) && (isset($newbom) && !empty($newbom))){
                foreach($products as $key => $val){
                    if(isset($newbom[$key])){
                        $this->error($key.__('Parameter %s can not be repeat', ''));
                    }
                }
            }
            //整理需要新增的数据
            if(isset($newbom) && !empty($newbom)){
                foreach($newbom as $key => $val){
                    if(!$val['Dosage'] || empty($val['Dosage'])){
                        $this->error($key.__('Usage cannot be empty', ''));
                    }
                    $insert_data[] = array(
                        'p_bn' => $params['product'],
                        'c_bn' => $key,
                        'level' => 1,
                        'createtime' => time(),
                        'updatetime' => time(),
                        'status' => $params['status'],
                        'unit' => $val['unit'],
                        'Dosage' => $val['Dosage'],
                        'comment' => $val['comment']
                    );
                }
                //执行新增数据
                Db::startTrans();
                $result = $this->model->insertAll($insert_data);
                if($result){
                    Db::commit();
                    $this->success();
                }else{
                    Db::rollback();
                    $this->error(__('Operation failed', ''));
                }
            }
            //整理需要更新的数据
            if(isset($products) && !empty($products)){
                foreach($products as $key => $val){
                    if(!$val['Dosage'] || empty($val['Dosage'])){
                        $this->error($key.__('Usage cannot be empty', ''));
                    }
                    $update_data[] = array(
                        'id' => $val['id'],
                        'updatetime' => time(),
                        'status' => $params['status'],
                        'unit' => $val['unit'],
                        'Dosage' => $val['Dosage'],
                        'comment' => $val['comment']
                    );
                }
                $this->model->saveAll($update_data);
            }
            $this->success();
        }
        if($this->request->get("type", [], 'trim') == 'bn'){
            $where3['p_bn'] = $ids;
            $list = $this->model->where($where3)->find();
        }else{
            $list = $this->model->find($ids);
        }
        if($status){
            $where['bn'] = $list->c_bn;
        }else{
            $where['bn'] = $list->p_bn;
        }

        $res = Db::name('products')->where($where)->find();
        $list->name = $res['name'];
        $this->view->assign("list", $list);
        if($status){
            $where1['p_bn'] = $list->c_bn;
        }else{
            $where1['p_bn'] = $list->p_bn;
        }

        $row_arr = $this->model->where($where1)->select();
        $row_arr = collection($row_arr)->toArray();
        foreach($row_arr as $key => $val){
            $where2['bn'] = $val['c_bn'];
            $row_arr[$key]['product'] = Db::name('products')->where($where2)->find();
            $row_arr[$key]['product']['access'] = $this->getAccessList[$row_arr[$key]['product']['access']];
        }
        $this->assignconfig('row', $row_arr);
        return $this->view->fetch();
    }
    /**
     * 编辑
     * @param null $ids
     * @param null $status
     */
    public function edit_bom($ids = null,$status = null){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');
            $products = $this->request->post("products/a",[],'trim');
            if(!isset($params['product']) || !$params['product']){
                $this->error(__('Parameter %s can not be empty', ''));
            }
//            $where['p_bn'] = $params['product'];
//            $has_product = $this->model->where($where)->find();
//            if(!empty($has_product)){
//                $this->error($params['product'].__('Product were exit', ''));
//            }
            if(isset($products['newbom'])){
                $newbom = $products['newbom'];
                unset($products['newbom']);
            }
            if((!isset($products) || empty($products)) && (!isset($newbom) || empty($newbom))){
                $this->error(__('Parameter %s can not be empty', ''));
            }
            //新增数据与更新数据判重
            if((isset($products) && !empty(isset($products))) && (isset($newbom) && !empty($newbom))){
                foreach($products as $key => $val){
                    if(isset($newbom[$key])){
                        $this->error($key.__('Parameter %s can not be repeat', ''));
                    }
                }
            }
            //整理需要新增的数据
            if(isset($newbom) && !empty($newbom)){
                foreach($newbom as $key => $val){
                    if(!$val['Dosage'] || empty($val['Dosage'])){
                        $this->error($key.__('Usage cannot be empty', ''));
                    }
                    $insert_data[] = array(
                        'p_bn' => $params['product'],
                        'c_bn' => $key,
                        'level' => 1,
                        'createtime' => time(),
                        'updatetime' => time(),
                        'status' => $params['status'],
                        'unit' => $val['unit'],
                        'Dosage' => $val['Dosage'],
                        'comment' => $val['comment']
                    );
                }
                //执行新增数据
                Db::startTrans();
                $result = $this->model->insertAll($insert_data);
                if($result){
                    Db::commit();
                    $this->success();
                }else{
                    Db::rollback();
                    $this->error(__('Operation failed', ''));
                }
            }
            //整理需要更新的数据
            if(isset($products) && !empty($products)){
                foreach($products as $key => $val){
                    if(!$val['Dosage'] || empty($val['Dosage'])){
                        $this->error($key.__('Usage cannot be empty', ''));
                    }
                    $update_data[] = array(
                        'id' => $val['id'],
                        'updatetime' => time(),
                        'status' => $params['status'],
                        'unit' => $val['unit'],
                        'Dosage' => $val['Dosage'],
                        'comment' => $val['comment']
                    );
                }
                $this->model->saveAll($update_data);
            }
            $this->success();
        }
        if($this->request->get("type", [], 'trim') == 'bn'){
            $where3['p_bn'] = $ids;
            $list = $this->model->where($where3)->find();
        }else{
            $list = $this->model->find($ids);
        }
        if($status){
            $where['bn'] = $list->c_bn;
        }else{
            $where['bn'] = $list->p_bn;
        }

        $res = Db::name('products')->where($where)->find();
        $list->name = $res['name'];
        $this->view->assign("list", $list);
        if($status){
            $where1['p_bn'] = $list->c_bn;
        }else{
            $where1['p_bn'] = $list->p_bn;
        }

        $row_arr = $this->model->where($where1)->select();
        $row_arr = collection($row_arr)->toArray();
        foreach($row_arr as $key => $val){
            $where2['bn'] = $val['c_bn'];
            $row_arr[$key]['product'] = Db::name('products')->where($where2)->find();
            $row_arr[$key]['product']['access'] = $this->getAccessList[$row_arr[$key]['product']['access']];
        }
        $this->assignconfig('row', $row_arr);
        return $this->view->fetch();
    }
    /**
     * 删除
     * @param null $ids
     */
    public function func_del($ids){
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
